<template>
  <view :data-theme="theme()" :class="theme() || ''">
    <view class="top-tabbar">
      <view :class="state_active == 0 ? 'tab-item active' : 'tab-item'" @click="stateFunc(0)">{{ $t('order.all_orders') }}
      </view>
      <view :class="state_active == 1 ? 'tab-item active' : 'tab-item'" @click="stateFunc(1)">
        {{ $t('order.pending_payment') }}</view>
      <view :class="state_active == 2 ? 'tab-item active' : 'tab-item'" @click="stateFunc(2)">
        {{ $t('order.pending_shipment') }}</view>
      <view :class="state_active == 3 ? 'tab-item active' : 'tab-item'" @click="stateFunc(3)">
        {{ $t('order.waiting_for_delivery') }}</view>
      <view :class="state_active == 4 ? 'tab-item active' : 'tab-item'" @click="stateFunc(4)">
        {{ $t('order.waiting_for_review') }}</view>
    </view>
    <!--列表-->
    <scroll-view scroll-y="true" class="scroll-Y" :style="'height:' + scrollviewHigh + 'px;'" lower-threshold="50"
      @scrolltolower="scrolltolowerFunc">
      <view :class="topRefresh ? 'top-refresh open' : 'top-refresh'">
        <view class="circle" v-for="(circle, n) in 3" :key="n"></view>
      </view>
      <view class="order-list">
        <view class="item" v-for="(item, index) in listData" :key="index">
          <view class="d-b-c pb38">
            <view class="item-dianpu" @click="toShop(item.shopSupplierId)">
              <view class="item-d-l mr10">
                <i class="icon iconfont icon-dianpu1"></i>
                <text class="fb gray3 f32" v-if="item.shopSupplierId > 0">{{ item.supplierName }}

                </text>
              </view>
              <view><i class="icon iconfont icon-jiantou"></i></view>
            </view>
            <view class="state">
              <text class="redF6">{{ item.orderStatusText }}</text>
            </view>
          </view>
          <view class="order-head d-b-c">
            <view>
              <text class="state-text">{{ item.orderSourceText }}</text>
              <text class="shop-name flex-1 fb">{{ $t('order.order_no_label', { place1: item.orderNo }) }}</text>
            </view>
          </view>
          <!--多个商品显示-->
          <view class="product-list pr" v-if="item.product.length > 1" @click="gotoOrder(item.orderId)">
            <scroll-view scroll-x="true">
              <view class="list d-s-c pr100">
                <view class="cover mr10" v-for="(img, num) in item.product" :key="num">
                  <image :src="img.productImage" mode="aspectFit"></image>
                </view>
              </view>
            </scroll-view>
            <view class="total-count">
              <view class="left-shadow"></view>
              <view class="price f22 theme-price"> HK$

                <text class="f40 theme-price">{{ item.payPrice }}</text>
              </view>
              <view class="count">{{ $t('order.total_items', { place1: item.totalNum }) }}</view>
            </view>
          </view>
          <!--一个商品显示-->
          <view class="one-product d-s-c" v-else @click="gotoOrder(item.orderId)">
            <view class="cover" v-for="(img, num) in item.product" :key="num">
              <image :src="img.productImage" mode="aspectFit"></image>
            </view>
            <view class="pro-info flex-1">{{ item.product[0].productName }}

            </view>
            <view class="total-count">
              <view class="left-shadow"></view>
              <view class="price theme-price f22"> HK$

                <text class="f40 theme-price" v-if="item.orderSource == 80">{{ (item.payPrice * 1 + item.advance.payPrice
                  * 1).toFixed(2)}}

                </text>
                <text class="f40 theme-price" v-else>{{ item.payPrice }}</text>
              </view>
              <view class="count">{{ $t('order.total_items', { place1: item.totalNum }) }}</view>
            </view>
          </view>
          <view class="order-bts presale" v-if="item.orderSource == 80">
            <view class="d-b-c line-h-50 f24 gray9">
              <view>{{ $t('order.deposit_paid') }}</view>
              <view>
                <text>{{ item.advance.payStatus == 20 ? $t("order.paid") : $t("order.to_be_paid") }}

                </text>HK${{ item.advance.payPrice }}
              </view>
            </view>
            <view class="d-b-c line-h-50 f24 gray9">
              <view>{{ $t('order.final_payment0') }}</view>
              <view>
                <text>{{ item.advance.payStatus == 20 && item.payStatus == 20 ? $t("order.paid") :
                  $t("order.to_be_paid")}}



                </text>HK${{ item.payPrice }}
              </view>
            </view>
            <template v-if="item.orderStatus == 10">
              <view class="d-e-c line-h-50 f24 gray9" v-if="
                item.advance && item.advance.payStatus == 20 && item.payStatus != 20
              ">
                <view v-if="nowOverTime(item.advance.endTime)"> {{ $t('order.final_payment_deadline') }}
                  <text class="redF11">{{ item.payEndTime }}

                  </text>
                </view>
                <view v-else-if="!nowOverTime(item.advance.endTime)"> {{ $t('order.final_payment_time0') }}
                  <text class="redF11">{{ item.advance.endTime }}

                  </text>
                </view>
              </view>
            </template>
            <view class="d-e-c line-h-50 f24 gray9" v-if="
              item.advance.payStatus == 10 && item.advance.orderStatus == 10 && item.orderStatus != 20
            ">
              <view v-if="
                !nowOverTime(item.advance.payEndTime) && !nowOverTime(item.advance.endTime)
              "> {{ $t('order.deposit_deadline') }}

                <text class="redF11">{{ countDown(item.advance.payEndTime) }}

                </text>
              </view>
            </view>

            <view class="d-e-c">
              <view class="d-e-c mt10" v-if="item.orderStatus == 21">
                <button @click="retractCancelOrder(item)" class="btn-gray-border">{{ $t('order.revoke_cancel') }}</button>
              </view>
              <view class="d-e-c mt10" v-if="item.orderStatus == 20">
                <button @click="deleteCancelOrder(item)" class="btn-gray-border">{{ $t('order.delete_order') }}</button>
              </view>
              <!-- 订单付款 -->
              <template v-if="item.advance.payStatus == 20 && item.payStatus == 10">
                <template v-if="
                  nowOverTime(item.advance.endTime) && item.orderStatus != 20 && item.orderStatus != 20
                ">
                  <view class="d-e-c mt10">
                    <button class="pay-btn theme-btn" @click="
                      gotoPage(
                        `/pages/order/cashier?orderId=${item.orderId}&orderType=80`
                      )
                      "> {{ $t('order.pay_final_payment') }}

                    </button>
                  </view>
                </template>
              </template>
              <!--
									定金拿里面的advance.payStatus 状态 10 未支付 20 已支付
									尾款拿外面的payStatus 状态 10 未支付 20 已支付
									@ApiModelProperty("预售订单定金支付结束时间")
									private Date payEndTime;
									@ApiModelProperty("预售结束时间")
									private Date endTime;
									@ApiModelProperty("订单状态10=>进行中，20=>已经取消，30=>已完成")
									private Integer orderStatus;
								 -->
              <view class="d-e-c mt10" v-if="
                item.advance.payStatus == 20 && item.advance.orderStatus == 10 && item.advance.moneyReturn == 1 && item.payStatus != 20
              ">
                <button class="pay-btn theme-borderbtn" @click="cancelAdvance(item.advance.orderAdvanceId)">
                  {{ $t('order.cancel_deposit') }}

                </button>
              </view>
              <template v-if="item.orderStatus == 10 && item.payStatus == 20 ">
                <template v-if="item.deliveryStatus == 10">
                  <button @click="cancelOrder(item)" class="theme-borderbtn"> {{ $t('order.apply_cancel') }}

                  </button>
                </template>
              </template>
              <!-- 预售未支付取消订单 -->
              <template v-if="item.orderSource == 80">
                <template v-if="
                  item.orderStatus == 10 && item.advance.payStatus == 10
                ">
                  <!-- <button @click="cancelOrder(item.orderId)" class="theme-borderbtn">申请取消</button> -->
                  <button @click="cancelAdvance(item.advance.orderAdvanceId)" class="theme-borderbtn">
                    {{ $t('order.apply_cancel') }}

                  </button>
                </template>
              </template>
              <view class="d-e-c mt10" v-if="
                item.advance.payStatus == 10 && !nowOverTime(item.advance.payEndTime) && item.orderStatus != 20
              ">
                <button class="pay-btn theme-btn" @click="
                  gotoPage(
                    '/pages/order/cashier?orderType=50&orderId=' +
                    item.advance.orderId
                  )
                  "> {{ $t('order.pay_deposit') }}

                </button>
              </view>
              <view class="d-e-c mt10" v-if="item.deliveryStatus == 20 && item.receiptStatus == 10">
                <button v-if="
                  item.payType == 20 && item.paySource == 'wx' && isSendWx
                " @click="wxOrder(item)" class="pay-btn theme-btn"> {{ $t('order.confirm_receipt') }}

                </button>
                <button v-else @click="orderReceipt(item)" class="pay-btn theme-btn"> {{ $t('order.confirm_receipt') }}

                </button>
              </view>
              <view class="d-e-c mt10" v-if="item.orderStatus == 30 && item.isComment == 0">
                <button class="pay-btn theme-btn" @click="gotoEvaluate(item.orderId)"> {{ $t('order.review') }}

                </button>
              </view>
            </view>

          </view>

          <view class="order-bts" v-else>
            <button v-if="item.orderStatus == 21" @click="retractCancelOrder(item)"
              class="btn-gray-border">{{ $t('order.revoke_cancel') }}</button>
            <button v-if="item.orderStatus == 20" @click="deleteCancelOrder(item)"
              class="btn-gray-border">{{ $t('order.delete_order') }}</button>
            <block v-if="item.orderStatus == 10">
              <!-- 未支付取消订单 -->
              <button @click="cancelOrder(item)" class="theme-borderbtn" v-if="item.payStatus == 10">
                {{ $t('order.cancel') }}

              </button>
              <!-- 已支付取消订单 -->
              <block v-if="item.payStatus == 20 && item.deliveryStatus == 10 && !notApplyCancel">
                <button @click="cancelOrder(item)" class="theme-borderbtn"> {{ $t('order.apply_cancel') }}
                </button>
              </block>
              <!-- 订单核销码 关闭时间 20250623-->
              <template v-if="item.payStatus == 20 && item.deliveryStatus == 10&&false">
                <block v-if="item.deliveryType == 20">
                  <button v-if="item.orderSource == 30 && item.assembleStatus == 20" @click="onQRCode(item.orderId)"
                    class="theme-borderbtn"> {{ $t('order.voucher_code') }}

                  </button>
                 
                  <button v-if="item.orderSource != 30" @click="onQRCode(item.orderId)" class="theme-borderbtn">
                    {{ $t('order.voucher_code') }}

                  </button>
                </block>
              </template>
              <!-- 订单付款 -->
              <block v-if="item.payStatus == 10"><button class="theme-btn" @click="onPayOrder(item.orderId)">
                  {{ $t('order.pay') }}

                </button>
              </block>
              <!-- 确认收货 -->
              <block v-if="item.deliveryStatus == 20 && item.receiptStatus == 10">
                <button v-if="
                  item.payType == 20 && item.paySource == 'wx' && isSendWx
                " class="theme-btn" @click="wxOrder(item)"> {{ $t('order.mini_program_confirm_receipt') }}

                </button>
                <button v-else class="theme-btn" @click="orderReceipt(item.orderId)"> {{ $t('order.confirm_receipt') }}

                </button>
              </block>
            </block>
            <!-- 订单评价 -->
            <button class="theme-btn" v-if="item.orderStatus == 30 && item.isComment == 0"
              @click="gotoEvaluate(item.orderId)">
              {{ $t('order.review') }}

            </button>
            <template v-if="item.assembleStatus == 10 && item.orderSource == 30">
              <button class="theme-btn" @click="gotoAssembleShare(item.product[0].billSourceId)">
                {{ $t('order.invite_friends') }}

              </button>
            </template>
          </view>
        </view>
        <view class="d-c-c p30" v-if="listData.length == 0 && !loading">
          <text class="iconfont icon-wushuju"></text>
          <text class="cont">{{ $t('order.no_records') }}</text>
        </view>
        <uni-load-more v-else :loadingType="loadingType"></uni-load-more>
      </view>
    </scroll-view>
    <!--核销二维码-->
    <Popup :show="isCodeImg" type="middle" @hidePopup="hideCodePopupFunc">
      <view class="ww100 p20 box-s-b">
        <image class="ww100" :src="codeImg" mode="widthFix"></image>
      </view>
    </Popup>
    <tabBar></tabBar>
  </view>
</template>

<script>
import Popup from "@/components/uni-popup.vue";
import uniLoadMore from "@/components/uni-load-more.vue";
import { pay } from "@/common/pay.js";
export default {
  components: {
    Popup,
    uniLoadMore
  },
  data() {
    return {
      /*手机高度*/
      phoneHeight: 0,
      /*可滚动视图区域高度*/
      scrollviewHigh: 0,
      /*状态选中*/
      state_active: 0,
      /*顶部刷新*/
      topRefresh: false,
      /*数据*/
      listData: [],
      /*数据类别*/
      dataType: "all",
      /*是否显示支付类别弹窗*/
      isPayPopup: false,
      /*支付方式*/
      pay_type: 20,
      /*订单id*/
      order_id: 0,
      /*最后一页码数*/
      last_page: 0,
      /*当前页面*/
      page: 1,
      /*每页条数*/
      list_rows: 10,
      /*有没有等多*/
      no_more: false,
      /*是否正在加载*/
      loading: true,
      /*是否显示核销二维码*/
      isCodeImg: false,
      codeImg: "",
      mchId: "",
      isSendWx: null
    };
  },
  computed: {
    /*加载中状态*/
    loadingType() {
      if (this.loading) {
        return 1;
      } else {
        if (this.listData.length != 0 && this.no_more) {
          return 2;
        } else {
          return 0;
        }
      }
    }
  },
  onLoad(e) {
    if (typeof e.dataType != "undefined") {
      this.dataType = e.dataType;
    }
    if (this.dataType == "payment") {
      this.state_active = 1;
    } else if (this.dataType == "received") {
      this.state_active = 3;
    } else if (this.dataType == "comment") {
      this.state_active = 4;
    } else if (this.dataType == "delivery") {
      this.state_active = 2;
    }
  },
  mounted() {
    this.init();
  },
  onShow() {
    /*获取订单列表*/
    this.page = 1;
    this.listData = [];
    setTimeout(() => {
      this.getData();
    }, 600);
    uni.setNavigationBarTitle({
			title: this.$t('user.my_orders')
		})
  },
  methods: {
    searchFunc() {
      let self = this;
      self.pageIndex = 1;
      self.listData = [];
      self.no_more = false;
      this.getData();
    },
    /*初始化*/
    init() {
      let self = this;
      uni.getSystemInfo({
        success(res) {
          self.phoneHeight = res.windowHeight;
          // 计算组件的高度
          let view = uni.createSelectorQuery().select(".top-tabbar");
          view.boundingClientRect(data => {
            let h = self.phoneHeight - data.height;
            self.scrollviewHigh = h;
          }).exec();
        }
      });
    },
    /*状态切换*/
    stateFunc(e) {
      let self = this;
      if (self.state_active != e) {
        self.page = 1;
        self.loading = true;
        self.state_active = e;
        switch (e) {
          case 0:
            self.listData = [];
            self.dataType = "all";
            break;
          case 1:
            self.listData = [];
            self.dataType = "payment";
            break;
          case 2:
            self.listData = [];
            self.dataType = "delivery";
            break;
          case 3:
            self.listData = [];
            self.dataType = "received";
            break;
          case 4:
            self.listData = [];
            self.dataType = "comment";
            break;
        }
        self.getData();
      }
    },
    /*可滚动视图区域到底触发*/
    scrolltolowerFunc() {
      let self = this;
      if (self.no_more) {
        return;
      }
      self.page++;
      if (self.page <= self.last_page) {
        self.getData();
      } else {
        self.no_more = true;
      }
    },
    /*获取数据*/
    getData() {
      let self = this;
      self.loading = true;
      let dataType = self.dataType;
      self._postBody("user/order/lists", {
        type: dataType,
        pageIndex: self.page,
        pageSize: self.list_rows
      }, function (res) {
        self.loading = false;
        self.listData = self.listData.concat(res.data.list.records);
        self.isSendWx = res.data.isSendWx;
        self.last_page = res.data.list.lastPage;
        if (res.data.list.records.length > 0) {
          self.mchId = res.data.list.records[0].mchId;
        }
        if (res.data.list.lastPage <= 1) {
          self.no_more = true;
        } else {
          self.no_more = false;
        }
      });
    },
    /*跳转页面*/
    gotoOrder(e) {
      this.gotoPage("/pages/order/order-detail?orderId=" + e);
    },
    /*支付方式选择*/
    onPayOrder(orderId) {
      let self = this;
      self.gotoPage("/pages/order/cashier?orderId=" + orderId);
    },
    /*确认收货*/
    orderReceipt(orderId) {
      let self = this;
      wx.showModal({
        title: this.$t("order.prompt"),
        content: this.$t("order.confirm_receive"),
        success: function (o) {
          if (o.confirm) {
            uni.showLoading({
              title: self.$t("order.processing")
            });
            self._post("user/order/receipt", {
              orderId: orderId
            }, function (res) {
              uni.hideLoading();
              uni.showToast({
                title: res.msg,
                duration: 2000,
                icon: "success"
              });
              self.listData = [];
              self.getData();
            });
          } else {
            uni.showToast({
              title: self.$t("order.cancel_receipt"),
              duration: 1000,
              icon: "none"
            });
          }
        }
      });
    },
    cancelAdvance(e) {
      let self = this;
      let order_id = e;
      uni.showModal({
        title: this.$t("order.prompt"),
        content: this.$t("order.confirm_cancel0"),
        success: function (o) {
          if (o.confirm) {
            uni.showLoading({
              title: self.$t("order.processing")
            });
            self._get("plus/advance/order/cancelFront", {
              orderAdvanceId: order_id
            }, function (res) {
              uni.hideLoading();
              uni.showToast({
                title: self.$t("order.operation_success"),
                duration: 2000,
                icon: "success"
              });
              self.listData = [];
              self.getData();
            });
          }
        }
      });
    },
    /*计算时分秒*/
    countDown(t) {
      let time = new Date(t) / 1000 - new Date() / 1000;
      //天数
      let day = Math.floor(time / (60 * 60 * 24));
      //取模（余数）
      let modulo = time % (60 * 60 * 24);
      //小时数
      let hour = Math.floor(modulo / (60 * 60));
      modulo = modulo % (60 * 60);
      //分钟
      let minute = Math.floor(modulo / 60);
      //秒
      let second = modulo % 60;
      day = this.convertTwo(day);
      hour = this.convertTwo(hour);
      minute = this.convertTwo(minute);
      second = this.convertTwo(second);
      let text = parseInt(day) > 0 ? parseInt(day) + this.$t("order.day") : "" + parseInt(hour) + this.$t("order.hour") + parseInt(minute) + this.$t("order.minute") + parseInt(second) + this.$t("order.second");
      return text;
    },
    retractCancelOrder(e) {
      let self = this;
      let orderId = e.orderId;
      let content = this.$t("order.confirm_revoke_cancel");
      uni.showModal({
        title: this.$t("order.prompt"),
        content: content,
        success: function (o) {
          if (o.confirm) {
            uni.showLoading({
              title: self.$t("order.processing")
            });
            self._post('user/order/retract', {
              orderId: orderId
            }, function (res) {
              uni.hideLoading();
              uni.showToast({
                title: self.$t("order.operation_success"),
                duration: 2000,
                icon: 'success'
              });
              self.searchFunc();
            });
          }
        }
      });
    },
    deleteCancelOrder(e) {
      let self = this;
      let orderId = e.orderId;
      let content = this.$t("order.confirm_delete_order");
      uni.showModal({
        title: this.$t("order.prompt"),
        content: content,
        success: function (o) {
          if (o.confirm) {
            uni.showLoading({
              title: self.$t("order.processing")
            });
            self._post('user/order/delete', {
              orderId: orderId
            }, function (res) {
              uni.hideLoading();
              uni.showToast({
                title: self.$t("order.operation_success"),
                duration: 2000,
                icon: 'success'
              });
              self.searchFunc();
            });
          }
        }
      });
    },
    /*取消订单*/
    cancelOrder(e) {
      /*
      @ApiModelProperty("是否多商户订单(0单订单，1多订单)")
      private Integer isMore;
      */
      let self = this;
      let orderId = e.orderId;
      let content = this.$t("order.confirm_cancel0");
      if (e.isMore == 1) {
        content = this.$t("order.cancel_order_prompt");
      }
      uni.showModal({
        title: this.$t("order.prompt"),
        content: content,
        success: function (o) {
          if (o.confirm) {
            uni.showLoading({
              title: self.$t("order.processing")
            });
            self._post("user/order/cancel", {
              orderId
            }, function (res) {
              uni.hideLoading();
              uni.showToast({
                title: self.$t("order.operation_success"),
                duration: 2000,
                icon: "success"
              });
              self.listData = [];
              self.getData();
            });
          }
        }
      });
    },
    /*去评论*/
    gotoEvaluate(e) {
      this.gotoPage("/pages/order/evaluate/evaluate?orderId=" + e);
    },
    /*核销码*/
    onQRCode(e) {
      let self = this;
      uni.showLoading({
        title: this.$t("order.loading")
      });
      self._get("user/order/qrcode", {
        orderId: e,
        source: self.getPlatform()
      }, function (res) {
        uni.hideLoading();
        self.isCodeImg = true;
        self.codeImg = res.data;
      });
    },
    nowOverTime(t) {
      let now = new Date().getTime();
      let time = new Date(t).getTime();
      console.log("now", now, "time", time, "t，", t);
      return now >= time;
    },
    /*关闭核销二维码*/
    hideCodePopupFunc() {
      this.isCodeImg = false;
    },
    toShop(id) {
      this.gotoPage("/pages/shop/shop?shopSupplierId=" + id);
    },
    /*分享拼团*/
    gotoAssembleShare(e) {
      let url = "/pages/plus/assemble/fight-group-detail/fight-group-detail?assembleBillId=" + e;
      this.gotoPage(url);
    },
    wxOrder(item) {
      let self = this;
      if (wx.openBusinessView) {
        wx.openBusinessView({
          businessType: "weappOrderConfirm",
          extraData: {
            merchant_id: self.mchId,
            merchant_trade_no: item.tradeNo,
            transaction_id: item.transactionId
          },
          success() {
            self._post("user/order/receipt", {
              orderId: item.orderId
            }, function (res) {
              uni.showToast({
                title: res.msg,
                duration: 2000,
                icon: "success"
              });
              self.listData = [];
              self.getData();
            });
          },
          fail() {
            //dosomething
          },
          complete() {
            //dosomething
          }
        });
      } else {
        //引导用户升级微信版本
      }
    }
  }
};
</script>

<style lang="scss">
@import url("css/myorder.css");
</style>
